<template>
  <PageWrapper contentFullHeight fixedHeight>
    <VxeBasicTable class="w-full h-full" ref="tableRef" v-bind="gridOptions">
      <template #action="{ row }">
        <a-space>
          <a-tooltip placement="bottom" v-if="hasEditPermission(row)">
            <template #title>
              <span>编辑</span>
            </template>
            <a-button type="link" size="small" @click="handleEdit(row)">
              <template #icon><Icon icon="clarity:note-edit-line" /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip placement="bottom" v-if="hasEditPermission(row)">
            <template #title>
              <span>删除</span>
            </template>
            <a-button type="link" danger size="small">
              <template #icon>
                <a-popconfirm placement="left" title="是否确认删除？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(row)">
                  <Icon icon="ant-design:delete-outlined" />
                </a-popconfirm>
              </template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </VxeBasicTable>
    <ConfigDrawer @register="registerDrawer" @success="reloadTableData" />
    <TableModal @register="registerModal" @success="reloadTableData" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { message } from "ant-design-vue";
import { Icon } from '@gui-pkg/components';
import { PageWrapper, BasicTableProps, useDrawer,useModal } from '@gui-pkg/antdcomponents';
import { VxeBasicTable, VxeGridInstance } from '@gui-pkg/antdcomponents';
import { columns, searchFormSchema } from './config.data';
import { getStationList, deleteStationData,deleteBatch } from '@/api/alerts/warningConfig';
import TableModal from './TableModal';
import ConfigDrawer from './ConfigDrawer.vue';
const [registerModal, { openModal }] = useModal();
const [registerDrawer, { openDrawer }] = useDrawer();
const tableRef = ref<VxeGridInstance>();

const LOGIN_USER_INFO_KEY: any = window.localStorage.getItem('LOGIN_USER_INFO_KEY');
const userData = JSON.parse(LOGIN_USER_INFO_KEY);

// 同步的权限检查函数
const hasEditPermission = (row) => {
  if (!userData || !userData.roles || !userData.deptName) {
    return false;
  }
  const isAdmin = userData.roles.includes("admin") || userData.roles.includes("city_role");
  if(isAdmin){
    return true;
  }

  if (!row || !row.town) {
    return false;
  }
  const isDeptMatch = userData.deptName === row.town;
  return isDeptMatch;
};

// 检查是否有批量删除权限（至少有一条记录有权限）
const hasBatchDeletePermission = computed(() => {
  if (!userData || !userData.roles || !userData.deptName) {
    return false;
  }
  const isAdmin = userData.roles.includes("admin") || userData.roles.includes("city_role");
  if(isAdmin){
    return true;
  }
  return false;
});

const gridOptions = reactive<BasicTableProps>({
  id: tableRef.value,
  keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  columns: columns,
  treeConfig: {
    childrenField: 'children',
    indent: 20,
    showIcon: true,
    iconOpen: 'vxe-icon-square-minus',
    iconClose: 'vxe-icon-square-plus'
  },
  toolbarConfig: {
    className: "vxe-toolbarConfig",
    buttons: [
      {
        content: '批量删除',
        buttonRender: {
          name: 'AButton',
          props: {
            type: 'primary',
            preIcon: 'ant-design:delete-outlined',
            disabled: !hasBatchDeletePermission.value // 根据权限禁用按钮
          },
          events: {
            click: () => handleBatchDelete(),
          },
        },
      },
      {
        content: '批量导入',
        buttonRender: {
          name: 'AButton',
          props: {
            type: 'primary',
            preIcon: 'ant-design:import-outlined',
            disabled: !hasBatchDeletePermission.value
          },
          events: {
            click: () => handleImport(),
          },
        },
      },
      {
        content: '新增配置',
        buttonRender: {
          name: 'AButton',
          props: {
            type: 'primary',
            preIcon: 'grommet-icons:add',
          },
          events: {
            click: () => handleCreate(),
          },
        },
      },
    ],
  },
  formConfig: {
    enabled: true,
    className: "vxe-formConfig",
    items: searchFormSchema,
  },
  height: 'auto',
  proxyConfig: {
    seq: true,
    ajax: {
      query: async ({ page, form }) => {
        const tableListData = await getStationList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...form,
        });
        console.log('tableListDatatableListDatatableListData',tableListData)
        return { list: tableListData.records,total:tableListData.total };
      },
    },
  },
});

function handleImport() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
  reloadTableData();
}

// 编辑配置
function handleEdit(row) {
  openDrawer(true, {
    record: row,
    isUpdate: true,
  });
  reloadTableData();
}

// 删除此配置
const handleDelete = async (row)=> {
  await deleteStationData(row.id);
  reloadTableData();
  message.success('删除成功');
}

const handleBatchDelete = async ()=> {
  const $table = tableRef.value
  if ($table) {
    const selectRecords = $table.getCheckboxRecords();
    if(selectRecords.length <= 0){
      message.error('请选中需要删除的记录');
      return;
    }

    // 检查权限：选中的记录必须都有权限才能删除
    const hasNoPermissionRecords = selectRecords.some(record => !hasEditPermission(record));
    if (hasNoPermissionRecords) {
      message.error('您没有权限删除选中的某些记录');
      return;
    }

    let ids = [];
    for(let i=0;i<selectRecords.length;i++){
      ids.push(selectRecords[i].id);
    }
    console.log('---------------batch',ids)
    await deleteBatch(ids);
    reloadTableData();
    message.success('删除成功');
  }
}

// 重新请求菜单表格数据
const reloadTableData = async () => {
  const tableListData = await getStationList({pageNum: 1, pageSize: 20 });
  tableRef.value.loadData(tableListData.records);
};
</script>
